package com.dmj.sqldsl.builder;

import static java.util.stream.Collectors.toList;

import com.dmj.sqldsl.builder.column.type.ColumnLambda;
import com.dmj.sqldsl.builder.condition.ConditionsBuilder;
import com.dmj.sqldsl.builder.config.EntityConfig;
import com.dmj.sqldsl.builder.config.GlobalConfig;
import com.dmj.sqldsl.model.DslUpdate;
import com.dmj.sqldsl.model.Where;
import java.util.Arrays;

public class UpdateWhereBuilder<T> {

  private final UpdateBuilder<T> updateBuilder;

  private final ConditionsBuilder conditionsBuilder;

  public UpdateWhereBuilder(UpdateBuilder<T> tUpdateBuilder, ConditionsBuilder conditionsBuilder) {
    this.updateBuilder = tUpdateBuilder;
    this.conditionsBuilder = conditionsBuilder;
  }

  @SafeVarargs
  public final <R> UpdateFinishBuilder<T, R> returning(ColumnLambda<T, R>... columnLambdas) {
    return new UpdateFinishBuilder<>(this, Arrays.stream(columnLambdas)
        .map(ColumnLambda::getColumnBuilder).collect(toList()));
  }

  protected DslUpdate toUpdate(EntityConfig config) {
    DslUpdate update = updateBuilder.toUpdate(config);
    update.setWhere(new Where(conditionsBuilder.build(config)));
    return update;
  }

  public DslUpdate toUpdate() {
    return this.toUpdate(GlobalConfig.getEntityConfig());
  }
}
